<template>
  <el-card class="box-card" v-if="details.name">
    <template #header>
      <div class="doc-details">
        <div class="doc-name">
          {{ details?.name }}
        </div>
        <div class="doc-author">
          <span style="margin-right: 10px">{{ details.author }}</span>于  <span style="font-weight: bold"> {{ details.uploadTime }} </span>  上传
        </div>
      </div>
      <div class="tool-buttons">
        <el-popover
            ref="popover"
            placement="bottom"
            width="200"
            trigger="hover">
          <template #reference>
            <el-icon class="detail-icon">
              <DetailIcon></DetailIcon>
            </el-icon>
          </template>
          <div style="font-size: 15px;font-weight: bold">
            详细信息
          </div>
          <div style="font-size: 11px">
            <div class="detail-cell">
              <span></span>上传人<span style="float: right">{{ details?.author }}</span>
            </div>
            <div class="detail-cell">
              <span></span>上传时间<span style="float: right">{{ details.uploadTime }}</span>
            </div>
            <div class="detail-cell">
              <span></span>阅读次数<span style="float: right">{{ details.readTimes }}</span>
            </div>
            <div class="detail-cell">
              <span></span>下载次数<span style="float: right">{{ details.downloadTimes }}</span></div>
          </div>
        </el-popover>
        <el-button v-if="details.suffixType==='8'" @click="clickEditMarkdown" class="utilButton edit-button">
          <el-icon class="util-icon">
            <EditPen/>
          </el-icon>
          {{ markMode !== 'preview' ? '关闭编辑' : '启动编辑' }}
        </el-button>
        <el-button class="utilButton download-button" @click="downloadDocument">
          <el-icon class="util-icon">
            <CommonDownloadIcon/>
          </el-icon>
          下载
        </el-button>
        <el-button class="utilButton full-button" @click="clickFull">
          <el-icon class="util-icon">
            <ScreenFullIcon/>
          </el-icon>
          全屏
        </el-button>
      </div>
    </template>
    <iframe v-if="details.suffixType!=='4'&&details.suffixType!=='8'" :src="src" id="mobsf" scrolling="auto"
            frameborder="0">
    </iframe>
    <div v-if="details.suffixType==='4'" style="height: 100%" id="mobsf">
      <div class="prev-button">
        <el-button size="small" @click="prevPhoto" class="photo-button left">
          <el-icon color="white">
            <ArrowLeftBold/>
          </el-icon>
        </el-button>
        <el-button size="small" @click="nextPhoto" class="photo-button right">
          <el-icon color="white">
            <ArrowRightBold/>
          </el-icon>
        </el-button>
      </div>
      <viewer :images="currentImage" rebuild>
        <img style="max-width: 20%;max-height: 20%;display: none" v-for="imgSrc in currentImage" :key="imgSrc"
             :src="imgSrc">
      </viewer>
    </div>
    <Transition name="mark" mode="out-in" appear>
      <MarkdownPreview :file-url="details.fileUrl"
                       v-model:mark-mode="markMode"
                       id="mobsf"
                       v-if="details.suffixType==='8'">
      </MarkdownPreview>
    </Transition>
  </el-card>
</template>
<script setup>
import {ref, watch, watchEffect} from 'vue'
import FrontApi from '@/api/front'
import screenfull from 'screenfull'
import CommonDownloadIcon from '@/components/common/CommonDownloadIcon'
import ScreenFullIcon from '@/components/common/ScreenFullIcon'
import DetailIcon from '@/components/common/DetailIcon'
import {download} from "@/api/request";
import MarkdownPreview from '@/components/common/MarkdownPreview'
import {ElNotification} from "element-plus";


const props = defineProps({
  url: String,
  docId: String
})

const emit = defineEmits(['prevPhoto'])
const src = ref('')
const details = ref({})
const imageList = ref([])
const imageDocIdList = ref([])
const currentImage = ref([])
// markdown模式
const markMode = ref('preview')
// 锁时间延长定时器
const timer = ref()

watch(() => props.docId, () => {
  if (timer.value) {
    markMode.value = 'preview'
    clearInterval(timer.value)
    console.log("销毁定时器")
    timer.value = ''
  }
})

watchEffect(() => {
  src.value = props.url
  if (!props.docId) return;
  FrontApi.getSpaceDocDetail(props.docId).then(res => {
    details.value = res.data
    if (res.data?.suffixType !== '4') return;
    if (currentImage.value.length === 0) {
      currentImage.value.push(res.data.fileUrl)
    } else {
      currentImage.value.shift()
      currentImage.value.push(res.data.fileUrl)
    }
    FrontApi.getImagesUnderDirectory(res.data.documentId).then(res => {
      imageList.value = []
      imageDocIdList.value = []
      res.data.forEach(item => {
        imageList.value.push(item.fileUrl)
        imageDocIdList.value.push(item.documentId)
      })
    })
  })
})

// markdown开始编辑模式
const clickEditMarkdown = () => {
  if (markMode.value === 'preview') {
    // 检查是否有人正在编辑
    FrontApi.checkMDEditPermission(props.docId).then((res) => {
      if (!res.data.flag) {
        ElNotification({
          title: 'warning',
          message: res.data.nickName + '正在编辑',
          type: 'warning',
          duration: 2000,
          offset: 100,
        })
      } else {
        markMode.value = 'editable'
        // 开启定时器，每20秒发送一次请求，续命
        timer.value = setInterval(() => {
          FrontApi.checkMDEditPermission(props.docId).then((res) => {
            if (res.data.flag) {
              console.log("锁续命成功！")
            }
          })
        }, 20000)
      }
    })
  } else {
    // 销毁定时器
    if (timer.value) {
      clearInterval(timer.value)
      console.log("销毁定时器")
      timer.value = ""
    }
    markMode.value = markMode.value === 'editable' ? 'preview' : 'editable'
  }
}

const downloadDocument = () => {
  download('/admin/front/downloadFile', {'spaceDocId': props.docId}, details.value.name);

}
const clickFull = () => {
  const ele = document.getElementById('mobsf');  //指定全屏区域元素
  screenfull.request(ele)
}


const prevPhoto = () => {
  let prevIndex = imageList.value.indexOf(currentImage.value[0]) - 1
  let prevDocId = imageDocIdList.value[prevIndex]
  if (prevIndex !== -1) {
    emit("prevPhoto", prevDocId)
  }
}

const nextPhoto = () => {
  let nextIndex = imageList.value.indexOf(currentImage.value[0]) + 1
  let nextDocId = imageDocIdList.value[nextIndex]
  if (nextIndex !== imageDocIdList.value.length) {
    emit("prevPhoto", nextDocId)
  }
}

</script>
<style scoped lang="scss">
iframe {
  width: 100%;
  height: 100%;
}

.doc-details {
  display: inline-block;
  width: 40%;
  background: var(--el-bg-color);
}

.detail-icon {
  font-size: 22px;
  margin-right: 1rem;
  cursor: pointer;
}

.doc-name {
  font-weight: bolder;
  font-size: 1.7rem;
  margin-left: 1rem;

}

.doc-author {
  margin-top: 1rem;
  font-size: 1.3rem;
  margin-left: 1rem;
}

:deep(.el-card__header) {
  padding: 8px;
  background: var(--el-bg-color);
}

.box-card {
  width: 100%;
  height: 100%;
}

.tool-buttons {
  display: flex;
  align-items: center;
  float: right;
  margin-top: 4px;
}

.download-button:active {
  background-color: #1a9b92a1 !important;
}

.utilButton {
  background-color: #1A9B92;
  color: white;
  border-color: #1A9B92;
  font-size: 12px;
}

.full-button:active {
  background-color: #e6e6e6 !important;
}

.full-button {
  background-color: white;
  border-color: #b8b4b4;
  color: black;
}

.util-icon {
  margin-right: 0.4rem;
}

.download {
  right: 150px;
}

.full-screen {
  right: 52px;
}

:deep(.el-card__body) {
  height: calc(100vh - 90px);
  padding: 5px;
}

.detail-cell {
  margin-top: 5px;
}

.photo-button {
  height: 40px;
  width: 40px !important;
  top: 50%;
  padding: unset;
  bottom: 10px;
  border-radius: 50%;
  position: absolute;
  background-color: #2e2b2b !important;
  color: #7f7f7f !important;
  border: 0;
  z-index: 9;
  --el-button-outline-color: none
}


.photo-button:hover {
  background-color: rgba(0, 0, 0, .8) !important;
}

.left {
  left: 15px;
}

.right {
  right: 15px;
}

.prev-button {
  width: 100%;
}

:deep(.viewer-prev) {
  display: none !important;
}

:deep(.viewer-next) {
  display: none !important;
}

.mark-enter-active {
  transition: all 0.5s ease;
}

.mark-leave-active {
  transition: all 0s ease;
}

.mark-enter-from,
.mark-leave-to {
  opacity: 0;
  transform: translateX(2rem);
}
.edit-button{
  background-color: #409eff !important;
  border-color: #409eff !important;
}

.edit-button:hover{
  color:#409eff !important;
  background-color: #dfeeff !important;
}
</style>